'use client'

import { useState, useRef, useEffect, Suspense } from "react"
import { useSearchParams, useRouter, usePathname } from "next/navigation"
import { useQuery, useQueryClient } from '@tanstack/react-query'

import { Bot, Menu } from "lucide-react"
import { ChatMessageList } from "@/components/chat/ChatMessage"
import { ChatInput, QuickQuestions } from "@/components/chat/ChatInput"
import { ChatSessionSidebar } from "@/components/chat/ChatSessionSidebar"
import { SseResponseEventEnum } from "@/types/fetch"
import {
  sendChatMessageStream,
  generateMessageId,
} from "@/utils/chat-api"
import { deleteChatMessagesAfter } from "@/apis/client/chat"
import { getContentDetail } from "@/apis/client/content"
import { Content } from "@/types/content"
import {
  useChatSessions,
  useChatSessionDetail,
  useCreateChatSession,
  useDeleteChatSession,
  useUpdateChatSessionTitle,
} from '@/hooks/useChat'
import {
  ChatMessage as ChatMessageType,
  generatingMessageProps,
} from "@/types/fetch"
import { ChatProvider, useChatContext } from "@/contexts/ChatContext"
import { Button } from "@/components/ui/button"
import { useAuth } from "@/lib/auth-context"
import { AgentFormPanel } from "@/components/chat/AgentFormPanel"

interface QuickQuestion {
  text: string
  emoji: string
  category: string
}

function ChatPageContent() {

  const searchParams = useSearchParams()
  const router = useRouter()
  const pathname = usePathname()
  const queryClient = useQueryClient()
  const { user, isLoading } = useAuth()
  const {
    messages,
    setMessages,
    isGenerating,
    setIsGenerating,
    currentChatId,
    setCurrentChatId,
    contentDetail,
    setContentDetail,
  } = useChatContext()
  const [abortController, setAbortController] = useState<AbortController | null>(null)


  const [sidebarCollapsed, setSidebarCollapsed] = useState(true) // 默认隐藏侧边栏
  const [inputInitialValue, setInputInitialValue] = useState('') // 输入框初始值
  const [contextProcessed, setContextProcessed] = useState(false) // 防止重复处理上下文


  // 使用React Query hooks
  const { data: chatSessions, refetch: refetchSessions } = useChatSessions()
  const { data: currentSessionDetail } = useChatSessionDetail(currentChatId || '')
  const createSessionMutation = useCreateChatSession()
  const deleteSessionMutation = useDeleteChatSession()
  const updateSessionTitleMutation = useUpdateChatSessionTitle()
  const messagesEndRef = useRef<HTMLDivElement>(null)


  useEffect(() => {
    const contentId = searchParams.get('contentId');
    if (contentId) {
      getContentDetail(contentId).then((res) => {
        setContentDetail(res)
      });
    }
  }, [searchParams, setContentDetail]);
  // 检测屏幕尺寸，桌面端默认显示侧边栏
  useEffect(() => {
    const checkScreenSize = () => {
      const isDesktop = window.innerWidth >= 768 // md断点
      setSidebarCollapsed(!isDesktop) // 桌面端显示，移动端隐藏
    }

    // 初始检测
    checkScreenSize()

    // 监听窗口大小变化
    window.addEventListener('resize', checkScreenSize)
    return () => window.removeEventListener('resize', checkScreenSize)
  }, [])

  // 进入页面时强制刷新左侧会话列表；页面重新可见时也刷新
  useEffect(() => {
    refetchSessions()

    const handleVisibility = () => {
      if (document.visibilityState === 'visible') {
        refetchSessions()
      }
    }
    document.addEventListener('visibilitychange', handleVisibility)
    return () => document.removeEventListener('visibilitychange', handleVisibility)
  }, [refetchSessions])

  // 从URL获取chatId，如果没有则创建新会话
  useEffect(() => {
    const chatIdFromUrl = searchParams?.get('chatId')

    if (chatIdFromUrl && chatIdFromUrl !== currentChatId) {
      // 切换到新的会话ID
      setCurrentChatId(chatIdFromUrl)

      // 会话历史记录会通过React Query自动加载
    } else if (!chatIdFromUrl && !currentChatId) {
      // URL中没有chatId且当前也没有会话，自动创建新会话
      handleNewSession()
    }
  }, [searchParams, currentChatId, setCurrentChatId,contentDetail])

  // 当会话详情加载完成时，更新消息列表
  useEffect(() => {
    // 如果正在生成，不要覆盖消息状态
    if (isGenerating) {
      return;
    }

    if (currentSessionDetail?.messages && currentSessionDetail.messages.length > 0) {
      // 有历史消息，显示历史记录
      const formattedMessages: ChatMessageType[] = currentSessionDetail.messages.map((msg,index) => ({
        id:index+'1',
        content: msg.content,
        role: msg.role as 'user' | 'assistant' | 'system',
        timestamp: new Date(msg.createdAt),
        isGenerating: false // 历史消息都不在生成中
      }))

      // 检查是否有正在生成的消息需要保留
      setMessages((prev) => {
        // 如果当前有正在生成的消息，需要保留其状态
        const currentGeneratingMessage = prev.find(msg => msg.isGenerating);
        if (currentGeneratingMessage) {
          // 合并历史消息和正在生成的消息
          const existingMessage = formattedMessages.find(msg => msg.id === currentGeneratingMessage.id);
          if (existingMessage) {
            // 如果历史消息中有这条消息，保持生成状态和当前内容
            existingMessage.isGenerating = true;
            existingMessage.content = currentGeneratingMessage.content; // 保留当前生成的内容
          } else {
            // 如果历史消息中没有，添加到末尾
            formattedMessages.push(currentGeneratingMessage);
          }
        }
        return formattedMessages;
      });

    } else if (currentSessionDetail && (!currentSessionDetail.messages || currentSessionDetail.messages.length === 0)) {
      // 没有历史消息，显示欢迎消息（但不要覆盖正在生成的消息）
      setMessages((prev) => {
        // 如果当前有正在生成的消息，保留它们
        const generatingMessages = prev.filter(msg => msg.isGenerating);
        if (generatingMessages.length > 0) {
          return prev; // 保持当前状态
        }
        
        // 没有正在生成的消息时才显示欢迎消息
        return [{
          id: "welcome",
          content: contentDetail?.agent?.welcomeText || "",
          role: "assistant",
          timestamp: new Date(),
          isGenerating: false
        }];
      });
    }
  }, [currentSessionDetail, isGenerating, setMessages,contentDetail])



  const quickQuestions: QuickQuestion[] = [

  ]

  // 处理从其他页面传来的问题，直接放入输入框
  useEffect(() => {
    const question = searchParams?.get('question')

    if (question && !contextProcessed) {
      setContextProcessed(true)
      // 将预设问题放入输入框
      setInputInitialValue(question)
      console.log('从URL参数获取问题:', question)

      // 立即清除URL中的question参数，避免刷新时重复回显
      const currentUrl = new URL(window.location.href)
      currentUrl.searchParams.delete('question')

      // 更新URL但不刷新页面
      window.history.replaceState({}, '', currentUrl.toString())

      console.log('已清除URL中的question参数')
    }
  }, [searchParams, contextProcessed])

  // 当聊天ID变化时，重置上下文处理状态
  useEffect(() => {
    setContextProcessed(false)
  }, [currentChatId])

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })
  }

  useEffect(() => {
    scrollToBottom()
  }, [messages])

  // 发送消息的核心逻辑
  const sendMessageCore = async (content: string, isRegenerate: boolean = false) => {
    if (!content.trim()) return

    // 如果不是重新生成，需要检查是否正在生成并设置加载状态
    if (!isRegenerate) {
      if (isGenerating) return
      setIsGenerating(true)
    }

    // 如果是重新生成，isGenerating 应该已经在重新生成函数中设置为 true

    // 添加用户消息（无论是否重新生成的内容都需要添加）
    const userMessage: ChatMessageType = {
      id: generateMessageId(),
      content: content.trim(),
      role: "user",
      timestamp: new Date(),
      isGenerating: false
    }

    setMessages((prev) => {
      const updatedMessages = [...prev, userMessage]

      // 同时更新React Query缓存中的会话详情
      if (currentChatId) {
        queryClient.setQueryData(
          ['chat', 'session', currentChatId],
          (oldData: any) => {
            if (!oldData) return oldData
            return {
              ...oldData,
              messages: updatedMessages.map(msg => ({
                id: msg.id,
                content: msg.content,
                role: msg.role,
                createdAt: msg.timestamp.toISOString(),
                isGenerating: msg.isGenerating
              }))
            }
          }
        )
      }

      return updatedMessages
    })

    // 创建AI回复消息（初始为空，用于流式更新）
    const aiMessageId = generateMessageId()
    const aiMessage: ChatMessageType = {
      id: aiMessageId,
      content: "",
      role: "assistant",
      timestamp: new Date(),
      isGenerating: true
    }


    setMessages((prev) => {
      const updatedMessages = [...prev, aiMessage]

 

      // 同时更新React Query缓存中的会话详情
      if (currentChatId) {
        queryClient.setQueryData(
          ['chat', 'session', currentChatId],
          (oldData: any) => {
            if (!oldData) return oldData
            const cacheMessages = updatedMessages.map(msg => ({
              id: msg.id,
              content: msg.content,
              role: msg.role,
              createdAt: msg.timestamp.toISOString(),
              isGenerating: msg.isGenerating
            }));



            return {
              ...oldData,
              messages: cacheMessages
            }
          }
        )
      }

      return updatedMessages
    })


    try {
      // 从 URL 读取 contentId
      const contentIdFromUrl = searchParams?.get('contentId')
      if (!contentIdFromUrl) {
        console.error('缺少 contentId，无法发送请求')
        // 更新AI消息为错误状态
        setMessages((prev) => prev.map(msg =>
          msg.id === aiMessageId
            ? {
                ...msg,
                content: "缺少 contentId 参数，请从正确入口进入或在 URL 中携带 contentId。",
                isGenerating: false
              }
            : msg
        ))
        setIsGenerating(false)
        setAbortController(null)
        return
      }
      // 创建用户消息用于API调用
      const tempUserMessage = {
        role: "user" as const,
        content: content.trim()
      }

      // 检查chatId
      let chatId = currentChatId
      if (!chatId) {
        console.error('发送消息时没有chatId，这不应该发生')
        return
      }

      // 创建新的AbortController
      const controller = new AbortController()
      setAbortController(controller)

      let accumulatedContent = ""

      // 发送流式请求
      await sendChatMessageStream(
        {
          chatId,
          messages: [tempUserMessage],
          stream: true,
          detail: true,
          contentId: contentIdFromUrl,
          variables:{
            prompt:contentDetail?.agent?.prompt || ''
          }
        },
        (data: generatingMessageProps) => {

          // 处理流式响应
          if (data.event === SseResponseEventEnum.answer && data.text) {
            accumulatedContent += data.text

            // 更新AI消息内容，保持生成状态
            setMessages((prev) => prev.map(msg =>
              msg.id === aiMessageId
                ? { ...msg, content: accumulatedContent, isGenerating: true }
                : msg
            ))
          } else if (data.event === SseResponseEventEnum.fastAnswer && data.text) {
            // 处理快速回答
            accumulatedContent += data.text

            // 更新AI消息内容，保持生成状态
            setMessages((prev) => prev.map(msg =>
              msg.id === aiMessageId
                ? { ...msg, content: accumulatedContent, isGenerating: true }
                : msg
            ))
          } else if (data.event === SseResponseEventEnum.answerDone || data.isAnswerDone) {
            // 回答完成
       
            setMessages((prev) => {
              const updatedMessages = prev.map(msg => {
                if (msg.id === aiMessageId) {
                  return { ...msg, isGenerating: false };
                }
                return msg;
              })

              // 同时更新React Query缓存中的会话详情
              if (currentChatId) {
                queryClient.setQueryData(
                  ['chat', 'session', currentChatId],
                  (oldData: any) => {
                    if (!oldData) return oldData
                    return {
                      ...oldData,
                      messages: updatedMessages.map(msg => ({
                        id: msg.id,
                        content: msg.content,
                        role: msg.role,
                        createdAt: msg.timestamp.toISOString(),
                        isGenerating: msg.isGenerating
                      }))
                    }
                  }
                )
              }

              return updatedMessages
            })
            setIsGenerating(false)
            setAbortController(null)

            setTimeout(() => {
                    // AI回复完成后，刷新会话列表
            queryClient.invalidateQueries({
              queryKey: ['chatSessions'],
              exact: false
            })
            }, 1000);
          }
        },
        controller
      )
    } catch (error) {
      console.error('发送消息失败:', error)

      // 更新AI消息为错误状态
      setMessages((prev) => prev.map(msg =>
        msg.id === aiMessageId
          ? {
              ...msg,
              content: "抱歉，我遇到了一些问题，请稍后再试。",
              isGenerating: false
            }
          : msg
      ))
      setIsGenerating(false)
      setAbortController(null)
    }
  }

  // 发送消息处理函数
  const handleSendMessage = async (content: string) => {
    await sendMessageCore(content, false)
  }
  console.log(JSON.stringify(messages),'messages');
  
  // 停止生成
  const handleStopGeneration = () => {
    if (abortController) {
      abortController.abort()
      setAbortController(null)
    }
    setIsGenerating(false)

    // 更新正在生成的消息状态，保留已生成的内容
    setMessages((prev) => {
      const updatedMessages = prev.map(msg =>
        msg.isGenerating ? { ...msg, isGenerating: false } : msg
      )

      // 同时更新React Query缓存中的会话详情
      if (currentChatId) {
        queryClient.setQueryData(
          ['chat', 'session', currentChatId],
          (oldData: any) => {
            if (!oldData) return oldData
            return {
              ...oldData,
              messages: updatedMessages.map(msg => ({
                id: msg.id,
                content: msg.content,
                role: msg.role,
                createdAt: msg.timestamp.toISOString(),
                isGenerating: msg.isGenerating
              }))
            }
          }
        )
      }

      return updatedMessages
    })
  }

  // 复制消息内容
  const handleCopyMessage = (content: string) => {
    navigator.clipboard.writeText(content)
    // 这里可以添加一个toast提示
  }





  // 重新生成消息
  const handleRegenerateMessage = async (messageId: string) => {
    if (isGenerating) {
      return;
    }

    // 找到要重新生成的AI消息
    const aiMessageIndex = messages.findIndex(msg => msg.id === messageId)
    if (aiMessageIndex === -1 || messages[aiMessageIndex].role !== 'assistant') {
      return;
    }

    // 找到对应的用户消息（AI消息的前一条应该是用户消息）
    const userMessageIndex = aiMessageIndex - 1
    if (userMessageIndex < 0 || messages[userMessageIndex].role !== 'user') {
      return;
    }

    const userMessage = messages[userMessageIndex]


    // 停止当前的生成过程
    if (abortController) {
      abortController.abort();
      setAbortController(null);
    }

    // 立即设置加载状态，让用户看到正在处理
    setIsGenerating(true);

    // 如果是真实会话，删除用户消息及其之后的所有消息
    let dbDeleteSuccess = false;
    if (currentChatId && !currentChatId.startsWith('temp_')) {
      try {

        // 先刷新会话详情，确保获取最新的数据库状态
        await queryClient.invalidateQueries({
          queryKey: ['chat', 'session', currentChatId]
        });

        // 等待数据重新加载
        await new Promise(resolve => setTimeout(resolve, 200));

        // 重新获取最新的会话详情
        const latestSessionDetail = queryClient.getQueryData(['chat', 'session', currentChatId]) as any;

        if (latestSessionDetail?.messages && latestSessionDetail.messages.length > 0) {
          // 找到对应的用户消息在数据库中的ID
          const dbMessages = latestSessionDetail.messages
          const userMessageContent = userMessage.content
          const userMessageTime = userMessage.timestamp


          // 查找所有匹配的用户消息（可能有重复）
          const matchingUserMessages = dbMessages.filter((msg: any) =>
            msg.role === 'user' && msg.content === userMessageContent
          );


          if (matchingUserMessages.length > 0) {
            // 如果有多条匹配，选择时间最接近的
            let targetMessage = matchingUserMessages[0];
            let minTimeDiff = Math.abs(new Date(targetMessage.createdAt).getTime() - userMessageTime.getTime());

            for (const msg of matchingUserMessages) {
              const timeDiff = Math.abs(new Date(msg.createdAt).getTime() - userMessageTime.getTime());
              if (timeDiff < minTimeDiff) {
                minTimeDiff = timeDiff;
                targetMessage = msg;
              }
            }

            await deleteChatMessagesAfter(currentChatId, targetMessage.id)
            dbDeleteSuccess = true;
          } else {
            // 通过用户消息内容和角色来删除
            await deleteChatMessagesAfter(currentChatId, undefined, {
              messageContent: userMessage.content,
              messageRole: 'user',
              messageTimestamp: userMessage.timestamp.toISOString()
            })
            dbDeleteSuccess = true;
          }
        } else {
        }
      } catch (error) { 
        console.error('删除数据库记录失败:', error)
        // 数据库删除失败，但继续前端操作
        dbDeleteSuccess = false;
      }
    }

    // 删除从用户消息开始的所有后续消息（包括用户消息、AI回复及之后的所有消息）
    const remainingMessages = messages.slice(0, userMessageIndex)


    setMessages(() => {
      // 同时更新React Query缓存中的会话详情
      if (currentChatId) {
        queryClient.setQueryData(
          ['chat', 'session', currentChatId],
          (oldData: any) => {
            if (!oldData) return oldData
            return {
              ...oldData,
              messages: remainingMessages.map(msg => ({
                id: msg.id,
                content: msg.content,
                role: msg.role,
                createdAt: msg.timestamp.toISOString(),
                isGenerating: msg.isGenerating
              }))
            }
          }
        )
      }

      return remainingMessages
    })

    // 如果数据库删除失败，强制刷新会话详情并等待
    if (!dbDeleteSuccess && currentChatId) {
      await queryClient.invalidateQueries({
        queryKey: ['chat', 'session', currentChatId]
      });

      // 等待一下让数据重新加载
      await new Promise(resolve => setTimeout(resolve, 500));
    }

    // 重新发送用户消息

    // 直接调用发送消息的核心逻辑，重新生成模式
    await sendMessageCore(userMessage.content, true); // true 表示这是重新生成

  }

  const handleQuickQuestion = (question: string) => {
    handleSendMessage(question)
  }

  // 处理会话选择
  const handleSessionSelect = (chatId: string, contentId?: string) => {
    if (isGenerating) {
      // 如果正在生成，可以选择弹窗提示用户
      if (!confirm("当前有消息正在生成，切换会话将中断，确定要切换吗？")) {
        return
      }
      // 用户确认切换，停止当前生成
      handleStopGeneration()
    }

    // 切换会话ID
    setCurrentChatId(chatId)

    // 更新URL
    router.push(`/chat?chatId=${chatId}${contentId ? `&contentId=${contentId}` : ''}`)

    // 清空消息列表，等待新会话数据加载
    setMessages([])
  }

  // 创建新会话
  const handleNewSession = () => {
    if (isGenerating) {
      if (!confirm("当前有消息正在生成，新建会话将中断，确定要继续吗？")) {
        return
      }
      handleStopGeneration()
    }

    // 立即创建一个临时的chatId
    const tempChatId = `temp_${Date.now()}`
    setCurrentChatId(tempChatId)

    // 更新URL
    router.push(`/chat?chatId=${tempChatId}&contentId=${contentDetail?.id}`)

    // 清空消息并显示欢迎语
    setMessages([
      {
        id: "welcome",
        content: contentDetail?.agent?.welcomeText || "你好！我是你的AI助手",
        role: "assistant",
        timestamp: new Date(),
        isGenerating: false
      }
    ])

    // 在后台创建真实会话
    createSessionMutation.mutate(undefined, {
      onSuccess: (data) => {
        // 创建成功后，用真实的chatId替换临时的
        const newChatId = data.id
        setCurrentChatId(newChatId)

        // 更新URL为真实的chatId
        router.replace(`/chat?chatId=${newChatId}&contentId=${contentDetail?.id}`)

        // 刷新会话列表
        refetchSessions()
      },
      onError: (error) => {
        console.error('创建新会话失败:', error)
        // 这里可以添加错误提示
      }
    })
  }

  // 删除会话
  const handleDeleteSession = (chatId: string) => {
    deleteSessionMutation.mutate(chatId, {
      onSuccess: () => {
        // 如果删除的是当前会话，则需要切换到新会话
        if (chatId === currentChatId) {
          handleNewSession()
        }
        // 刷新会话列表
        refetchSessions()
      },
      onError: (error) => {
        console.error('删除会话失败:', error)
      }
    })
  }

  // 更新会话标题
  const handleUpdateTitle = (chatId: string, newTitle: string) => {
    updateSessionTitleMutation.mutate({ chatId, title: newTitle }, {
      onSuccess: () => {
        // 刷新会话列表以显示新标题
        refetchSessions()
      },
      onError: (error) => {
        console.error('更新标题失败:', error)
      }
    })
  }

  if (isLoading) {
    return (
      <div className="h-[100%] bg-blue-50 flex items-center justify-center">
        <div className="text-gray-700">正在检查登录状态…</div>
      </div>
    )
  }

  if (!user) {
    return (
      <div className="h-[100%] bg-blue-50 flex items-center justify-center p-6">
        <div className="bg-white border rounded-lg shadow-sm p-6 text-center">
          <div className="text-xl font-semibold">需要登录</div>
          <div className="text-gray-600 mt-2">请先登录后使用聊天功能。</div>
        </div>
      </div>
    )
  }

  return (
    <div className="h-[100%] bg-blue-50 flex flex-col">
      {/* 页面头部 */}
      <header className="bg-white border-b border-blue-200 p-3 flex items-center justify-between shadow-sm z-10  md:hidden">
        <div className="flex items-center gap-2">
          <Button
            variant="ghost"
            size="icon"
            onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
            className="md:hidden" // 只在移动端显示
          >
            <Menu className="h-5 w-5 text-blue-600" />
          </Button>
        </div>

      </header>

      <div className="flex-1 flex overflow-hidden">
        {/* 侧边栏 */}
        <ChatSessionSidebar
          currentChatId={currentChatId}
          onSessionSelect={handleSessionSelect}
          onNewSession={handleNewSession}
          isCollapsed={sidebarCollapsed}
          onToggleCollapse={() => setSidebarCollapsed(!sidebarCollapsed)}
        />

        {/* 聊天主界面 */}
        <main className="flex-1 flex flex-col bg-white overflow-hidden">
          {/* 智能体信息 - 占位居中显示 */}
          <div className="flex justify-center py-4 border-gray-100">
            <div className="bg-white rounded-full px-4 py-2 shadow-sm border border-gray-200 flex items-center gap-2">
              <img src={contentDetail?.cover?.url || "/placeholder.svg"} alt={contentDetail?.title || '无标题'} className="w-8 h-8 rounded-full" />
              <h1 className="text-lg font-semibold text-gray-800"> {contentDetail?.title || '无标题'} </h1>
            </div>
          </div>

          {/* 消息列表 */}
          <div className="flex-1 overflow-y-auto p-4 md:p-6 space-y-6">
            <ChatMessageList
              messages={messages}
              onCopy={handleCopyMessage}
              onRegenerate={handleRegenerateMessage}
              isGenerating={isGenerating}
            />
            <div ref={messagesEndRef} />
          </div>

          {/* 输入区域 */}
          <div className="border-t border-blue-200 bg-white p-4 md:p-6">
            {/* 快捷问题 */}
            {/* <QuickQuestions
              questions={quickQuestions}
              onQuestionClick={handleQuickQuestion}
            /> */}

            {/* 输入框 */}
            <ChatInput
              onSendMessage={handleSendMessage}
              isGenerating={isGenerating}
              onStopGeneration={handleStopGeneration}
              initialValue={inputInitialValue} // 传递初始值
            />
          </div>
        </main>

        {/* 右侧表单面板组件 */}
        <AgentFormPanel
          agent={contentDetail?.agent}
          disabled={isGenerating}
          onSend={(content) => handleSendMessage(content)}
        />
      </div>
    </div>
  )
}

export default function ChatPage() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <ChatProvider>
        <ChatPageContent />
      </ChatProvider>
    </Suspense>
  )
}